package com.woniu.inlet.web;

import com.woniu.command.Command;
import com.woniu.command.userCommand.AddUserCommand;
import com.woniu.command.userCommand.DeleteUserCommand;
import com.woniu.command.userCommand.UpdateUserCommand;
import com.woniu.inlet.vo.UserVo;
import com.woniu.outlet.po.UserPo;
import com.woniu.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public ResponseEntity<List<UserVo>> findUsers() throws Exception{
        List<UserPo>  userPos =  userService.findUsers();
        List<UserVo> userVos = new ArrayList<>();
        //对象的深拷贝
        for (UserPo item : userPos){
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(item,userVo);
            userVos.add(userVo);
        }
        return new ResponseEntity<>(userVos, HttpStatus.OK);
    }


    @PostMapping("/add")
    public ResponseEntity<String> addUser(UserPo userPo){
        Command command = new AddUserCommand();
        command.execute(userPo);
        return new ResponseEntity<>("添加成功",HttpStatus.OK);
    }

    @PostMapping("/update")
    public ResponseEntity<String> updateUser(UserPo userPo){
        Command command = new UpdateUserCommand();
        command.execute(userPo);
        return new ResponseEntity<>("修改成功",HttpStatus.OK);
    }

    @PostMapping("/delete")
    public ResponseEntity<String> deleteUser(Integer id){
        Command command = new DeleteUserCommand();
        command.execute(id);
        return new ResponseEntity<>("删除成功",HttpStatus.OK);
    }


}
